package com.mall.common.util.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author zhoufeng
 *
 */
public class IOUtil {
	
	private static final Logger log = LoggerFactory.getLogger(IOUtil.class);


	public static final String DEFAULT_CHARSET = "UTF-8"; 
	
	/**
	 * 将输入流的数据转换为string
	 * @param in
	 * @param charsetName
	 * @return
	 */
	public static String readStringFromStream(InputStream in , String charsetName){
		if(charsetName == null){
			charsetName = DEFAULT_CHARSET ;
		}
		StringBuilder str = new StringBuilder() ;
		Reader reader = null ;
		try {
			reader = new InputStreamReader(in, charsetName);
			char[] buf = new char[1024];
			int len = -1 ;
			while((len = reader.read(buf)) > 0){
				str.append(buf, 0, len);
			}
		} catch (IOException e) { 
			log.error(e.getMessage(),e);
		}finally{
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					log.error(e.getMessage(),e);
				}
			}
		}
		return str.toString();
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		String str = readStringFromStream(new FileInputStream("/Users/zhoufeng/machine.txt"), null) ;
		System.out.println(str); 
	}

}
